﻿/*
 * The copyright statement below is for NLog.
 * See http://nlog-project.org for more information.

Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of Jaroslaw Kowalski nor the names of its
  contributors may be used to endorse or promote products derived from this
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using Authorit.API.Configuration;
using AuthoritExtensibility;
using PluginLogger;
using SyncHeadings.Properties;

namespace SyncHeadings
{
	/// <summary>
	/// Provides data and methods for communicating with the Author-it application.
	/// </summary>
	/// <seealso href="http://devhub.author-it.com/Library/#b4291t4086"/>
	internal class PluginManager : IPlugin
	{
		#region Fields (4) 

		/// <summary>
		/// Instance of the <see cref="Config"/> class used to read the configuration settings for the plugin
		/// </summary>
		private Config config;
		/// <summary>
		/// Local instance of the <see cref="LoggerWrapper"/> class.
		/// </summary>
		private LoggerWrapper logger;
		/// <summary>
		/// Local name for the logger.
		/// </summary>
		/// <remarks>This name should be the same for all loggers in the project.</remarks>
		/// <seealso href="http://nlog-project.org/doc/2.0/sl3/html/P_NLog_LogEventInfo_LoggerName.htm"/>
		private const string loggerName = "SyncHeadingsLogger";
		/// <summary>
		/// Instance of the <see cref="AitApplicationProxy"/> class for the plug-in.
		/// </summary>
		/// <seealso href="http://devhub.author-it.com/Library/#b4291t4087"/>
		private AitApplicationProxy pluginProxy;

		#endregion Fields 

		#region Constructors (1) 

		/// <summary>
		/// Initializes a new instance of the <see cref="PluginManager"/> class.
		/// </summary>
		/// <param name="proxy">Instance of <see cref="AitApplicationProxy"/> that Author-it passes to the plug-in.</param>
		/// <seealso href="http://devhub.author-it.com/Library/#b4291t4087">The AitApplicationProxy</seealso>
		/// <seealso href="http://devhub.author-it.com/Library/#b4291t4091">ContextMenuAddArgs</seealso>
		public PluginManager(AitApplicationProxy proxy)
		{
			this.config = new Config();
			string nlogConfigFile = config.NLogConfigFileName;
			string logFile = config.LogFileName;
			logger = new LoggerWrapper(loggerName, nlogConfigFile, logFile);

			pluginProxy = proxy;
			ContextMenuAddArgs contextArgs = new ContextMenuAddArgs();
			try
			{
				contextArgs.PluginName = Resources.PluginNameContext;
				logger.WriteResourceRead(ReflectionUtility.GetPropertyName(() => Resources.PluginNameContext), contextArgs.PluginName);
				contextArgs.IconImage = Resources.sync_16;
				logger.WriteResourceRead(ReflectionUtility.GetPropertyName(() => Resources.sync_16), contextArgs.IconImage.ToString());
			}
			catch (Exception ex)
			{
				logger.WriteFatalException(LogEventType.ReadResourceFailed, ex);
				throw;
			}
			try
			{
				contextArgs.SelectedObjectsMin = config.MinimumSelectedObjects;
				logger.WriteSettingRead(ReflectionUtility.GetPropertyName(() => Settings.Default.MinimumSelectedObjects), contextArgs.SelectedObjectsMin.ToString());
			}
			catch (Exception ex)
			{
				logger.WriteFatalException(LogEventType.ReadSettingFailed, ex);
				throw;
			}
			try
			{
				contextArgs.SelectedObjectsTypes = new ObjectType[] { ObjectType.Topic };
				contextArgs.OnClick = clickHandlerContext;
				pluginProxy.AddPluginToObjectContextMenu(contextArgs);
				logger.WriteInfo(LogEventType.OperationSuccess);
			}
			catch (Exception ex)
			{
				logger.WriteFatalException(LogEventType.OperationFailed, ex);
				throw;
			}
			//TODO: Implement launching from book editor to synchronize headingsToCheck for all topics in book - requires AIT v5.5.267.13925 or later

			//TODO: Implement main toolbar button to find topics with empty headings and sync them?
			//ToolbarAddArgs toolbarArgs = new ToolbarAddArgs();
			//toolbarArgs.IconImage = Resources.sync_32;
			//toolbarArgs.TargetButtonName = Resources.VersionFormatString;
			//toolbarArgs.Tooltip = Resources.ToolbarButtonTooltip;
			//toolbarArgs.TargetGroupName = Settings.Default.ToolbarTargetGroup;
			//toolbarArgs.PluginName = Settings.Default.ToolbarPluginName;
		}

		#endregion Constructors 

		#region Methods (3) 

		// Private Methods (3) 

		/// <summary>
		/// Handles the click event for the context menu item
		/// </summary>
		/// <param name="sender">Object that triggered the event</param>
		/// <param name="e">Arguments for the event</param>
		/// <seealso cref="SyncHeadingsForm"/>
		private void clickHandlerContext(object sender, AuthoritEventArgs e)
		{
			try
			{
				SyncHeadingsForm syncForm = new SyncHeadingsForm(e, config);
				System.Windows.Forms.DialogResult result = syncForm.ShowDialog();
				switch (result)
				{
					case System.Windows.Forms.DialogResult.Abort:
						break;

					case System.Windows.Forms.DialogResult.Cancel:
						break;

					case System.Windows.Forms.DialogResult.Ignore:
						break;

					case System.Windows.Forms.DialogResult.No:
						break;

					case System.Windows.Forms.DialogResult.None:
						break;

					case System.Windows.Forms.DialogResult.OK:
						RefreshFolder(e);
						RefreshObjects(e, RefreshType.ObjectUpdated);
						break;

					case System.Windows.Forms.DialogResult.Retry:
						break;

					case System.Windows.Forms.DialogResult.Yes:
						break;

					default:
						break;
				}
				syncForm.Dispose();
				logger.WriteInfo(LogEventType.OperationSuccess);
			}
			catch (Exception ex)
			{
				logger.WriteLog(NLog.LogLevel.Fatal, LogEventType.OperationFailed, ex.Message);
			}
		}

		/// <summary>
		/// Refreshes the current folder in the Author-it Editor.
		/// </summary>
		/// <param name="args">Instance of <see cref="AuthoritEventArgs"/> for the event.</param>
		/// <seealso href="http://devhub.author-it.com/Library/#b4291t4078">AuthoritEventArgs</seealso>
		private void RefreshFolder(AuthoritEventArgs args)
		{
			LibraryRefreshArgs refreshArgs = new LibraryRefreshArgs();
			refreshArgs.Type = LibraryRefreshType.FolderRefresh;
			try
			{
				pluginProxy.RefreshLibrary(refreshArgs);
				logger.WriteInfo(LogEventType.OperationSuccess, args.Username, null, String.Empty);
			}
			catch (Exception ex)
			{
				logger.WriteLog(NLog.LogLevel.Error, LogEventType.OperationFailed, args.Username, null, String.Empty, ex.Message);
			}
		}

		/// <summary>
		/// Refreshes the selected objects in the Author-it Editor.
		/// </summary>
		/// <param name="args">Instance of <see cref="AuthoritEventArgs"/> for the event.</param>
		/// <param name="reason">One of the valid <see cref="RefreshType"/> values that specifies the reason for refreshing the object(s).</param>
		/// <seealso href="http://devhub.author-it.com/Library/#b4291t4081">ObjectRefreshArgs</seealso>
		private void RefreshObjects(AuthoritEventArgs args, RefreshType reason)
		{
			foreach (int objectId in args.SelectedObjectIDs)
			{
				try
				{
					ObjectRefreshArgs refreshArgs = new ObjectRefreshArgs();
					refreshArgs.ObjectID = objectId;
					refreshArgs.Reason = reason;
					logger.WriteInfo(LogEventType.OperationSuccess, args.Username, objectId, String.Empty);
				}
				catch (Exception ex)
				{
					logger.WriteLog(NLog.LogLevel.Error, LogEventType.OperationFailed, args.Username, objectId, String.Empty, ex.Message);
				}
			}
		}

		#endregion Methods 
	}
}